package com.xjj.service.service.serviceimpl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xjj.entity.Menu;
import com.xjj.service.mapper.MenuMapper;
import com.xjj.service.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author : 王泰元
 * @date : 2022/10/20 10:33
 */
@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements MenuService {
    private final String CACHE_MENU_KEY = "dashboard:menu:role-";

    @Autowired
    private MenuMapper menuMapper;

    @Autowired
    RedisTemplate<String, Object> redisTemplate;

    @Override
    public List<Menu> getAll() {
        Object o = redisTemplate.opsForValue().get(CACHE_MENU_KEY + 0);
        if (o != null) {
            return (List<Menu>) o;
        }

        QueryWrapper<Menu> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("pid", 0);
        List<Menu> menus = menuMapper.selectList(queryWrapper);

        for (Menu pMenu : menus) {
            queryWrapper.clear();
            queryWrapper.eq("pid", pMenu.getId());
            pMenu.setSubMenu(menuMapper.selectList(queryWrapper));
        }

        redisTemplate.opsForValue().set(CACHE_MENU_KEY + 0, menus);
        return menus;
    }

    @Override
    public List<Menu> getMenusByRoleId(Integer roleId) {
        Object o = redisTemplate.opsForValue().get(CACHE_MENU_KEY + roleId);
        if (o != null) {
            return (List<Menu>) o;
        }

        List<Menu> menus = menuMapper.getPMenusByRoleId(roleId);
        for (Menu pMenu : menus) {
            pMenu.setSubMenu(menuMapper.getSubMenusByRoleId(roleId, pMenu.getId()));
        }

        redisTemplate.opsForValue().set(CACHE_MENU_KEY + roleId, menus);

        return menus;
    }
}
